from wxauto import *
import webot2 as webot
import time
from queue import Queue
from threading import Thread
import sys

me = 'G.L.Wang'
allowing_people = 'File Transfer'

wx = WeChat()
webot.test = not False
_msg_queue = Queue(128)
_msg_stamp = 0
_on_process = False


def sends(msg):
    wx.ChatWith(allowing_people)
    WxUtils.SetClipboard(msg)
    wx.SendClipboard()
    return wx.GetLastMessage[2]


def start_and_test():
    start_comment = "注意：此微信已被ChatGPT托管！\r\n不要谈论隐私信息！\r\nAttention: WeChat is now being taken over by ChatGPT! \r\nPlease be careful not to discuss any private information!"
    start_comment2 = '发送"#help"查看帮助信息\r\nsend "#help" to get help\r\n'
    try:
        webot.start()
        sends(start_comment)
        sends(start_comment2)
        print('starting...')
        now_time = time.strftime(
            '%Y年%m月%d日%H点%M分', time.localtime(time.time()))
        answer = webot.make_a_question(
            f'你好，我是{allowing_people}，现在是{now_time}，很高兴见到你。')
        return True, answer
    except Exception as e:
        webot.screenshot()
        webot.quit()
        return False, str(e)


def asking_thread():
    global _msg_stamp, _on_process
    while 1:
        msg = _msg_queue.get()
        if msg =='#quit':
            break
        while not _msg_queue.empty():
            _msg = _msg_queue.queue[0]
            if _msg.strip().startswith('#'):
                break
            msg = f'{msg}\r\n{_msg_queue.get()}'
        # print(msg)
        try:
            if msg == '#start':
                if _on_process:
                    continue
                ok, msg = start_and_test()
                if not ok:
                    _msg_stamp = sends(f'  启动失败。\r\nFailed to start.{msg}')
                    continue
                _msg_stamp = sends(f'  {msg}')
                _on_process = True
                continue
            if not _on_process:
                continue
            if msg == '#exit':
                webot.close()
                _msg_stamp = sends('  Bye~')
                _on_process = False
                continue
            if msg == '#reload':
                webot.reload()
                _msg_stamp = sends('  Reloaded')
                continue
            if msg == '#new':
                webot.new_topic()
                continue
        except Exception as e:
            webot.quit()
            _on_process = False
            msg = f"  抱歉，发生了一些错误，程序已退出。\r\nSorry,something went wrong, program exited.\r\n{e}"
            _msg_stamp = sends(msg)
            continue

        try:
            msg = webot.make_a_question(msg)
            msg = f'  {msg}'
            _msg_stamp = sends(msg)
        except Exception as e:
            webot.screenshot()
            webot.reload()
            msg = f"  抱歉，发生了一些错误。\r\nSorry, something went wrong.\r\n{e}"
            _msg_stamp = sends(msg)
    print('asking thread exit')


def main():
    global _msg_stamp

    try:
        _ask_thread = Thread(target=asking_thread)
        _ask_thread.start()
        _msg_queue.put('#start')
        _, _, _msg_stamp = wx.GetLastMessage
        while "i'm pretty":
            who, msg, timestamp = wx.GetLastMessage
            if timestamp <= _msg_stamp:
                time.sleep(0.5)
                continue
            time.sleep(0.25)
            if timestamp <= _msg_stamp:
                continue
            print(f'{who}: {msg}')
            if not _on_process:
                if msg.strip() == '#start':
                    _msg_queue.put('#start')
                _msg_stamp = timestamp
                continue
            if who != allowing_people and who != me:
                _msg_stamp = timestamp
                continue
            cmd = msg.strip()
            if cmd == '#exit' or cmd == '#bye' or cmd == '#quit':
                _msg_queue.put('#exit')
                _msg_stamp = timestamp
                continue
            if cmd == '#close':
                break
            if cmd == '#reload':
                _msg_queue.put('#reload')
                _msg_stamp = timestamp
                continue
            if msg == '#help':
                msg = '#help:\t显示帮助\tshow help\r\n#start:\t启动程序\tstart the program\r\n#exit:\t退出\t exit chat\r\n#new:\t开始新话题\tstart a new topic'
                _msg_stamp = sends(msg)
                continue
            if msg == '#new':
                _msg_queue.put('#new')
                _msg_stamp = timestamp
                continue
            _msg_queue.put(msg)
            _msg_stamp = timestamp
            time.sleep(0.25)
    except Exception as e:
        print(e)
        print('exit')
    except KeyboardInterrupt:
        pass
    _msg_queue.put('#quit')

if __name__ == '__main__':
    webot.test = True
    if len(sys.argv) > 1:
        if sys.argv[1] == '-t':
            webot.test = True
            sys.argv = sys.argv[1:]
    if len(sys.argv) > 1:  
        allowing_people = sys.argv[1]
    wx.ChatWith(allowing_people)
    main()